# Definition for singly-linked list.
class ListNode:
    def __init__(self, x):
        self.val = x
        self.next = None


class Solution:
    def reverseKGroup(self, head: ListNode, k: int) -> ListNode:
        mid_list, now_note = [], ListNode(0)
        tou = now_note
        try:
            while True:
                while len(mid_list) < k:
                    mid_list.append(head)
                    head = head.next
                while mid_list:
                    now_note.next = mid_list.pop(-1)
                    now_note = now_note.next
        except:
            if mid_list:
                now_note.next = mid_list[0]
            else:
                now_note.next = None
            return tou.next

